<template>
  <div>
    <el-card style='margin: 20px 0'>
      <CategorySelect @getCategoryId='getCategoryId' :show='!isShowTable'></CategorySelect>
    </el-card>

    <el-card>
      <div v-show='isShowTable'>
        <el-button type="primary" icon='el-icon-plus' style='margin: 10px 0' :disabled='!category3Id' @click='addAttr'>添加属性</el-button>
        <el-table  :data= 'attrList' border >
          <el-table-column label="序号" type="index" width='80' align="center"></el-table-column>
          <el-table-column label="属性名称" width='150' align="center" prop='attrName'></el-table-column>
          <el-table-column label="属性值列表">
            <template v-slot='{row}'>
              <el-tag type='primary' v-for='attrValue in row.attrValueList' :key='attrValue.id' style='margin: 0 10px'>{{attrValue.valueName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width='150' align="center">
            <template v-slot='{row}'>
              <el-button type="warning" size='mini' icon='el-icon-edit' @click='updateAttr(row)'></el-button>
              <el-button type="danger" size='mini' icon='el-icon-delete'></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加修改属性静态 -->
      <div v-show='!isShowTable'>
        <el-form :inline="true" :model='attrInfo'>
          <el-form-item label="属性名">
            <el-input  placeholder="请输入属性名" v-model='attrInfo.attrName'></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" icon='el-icon-plus' @click='addAttrValue' :disabled='!attrInfo.attrName'>添加属性值</el-button>
        <el-button type="" @click='isShowTable=true'>取消</el-button>

        <el-table border style='margin: 10px 0' :data='attrInfo.attrValueList'>
          <el-table-column label="序号" type="index" width='80' align="center"></el-table-column>
          <el-table-column label="属性值">
            <template v-slot='{row, $index}'>
              <!-- row是attrInfo.attrValueList的对应每一项 -->
              <!-- 属性值input  span来回切换 -->
              <el-input 
                size='mini' 
                placeholder="请输入属性值名称" 
                v-model='row.valueName' 
                v-if='row.flag' 
                @blur='toLook(row)' 
                @keyup.native.enter='toLook(row)'
                :ref='$index'
              ></el-input>
              <span v-else @click='toEdit(row, $index)'>{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width='150'>
            <template v-slot='{row, $index}'>
              <!-- 气泡弹出框 -->
              <el-popconfirm :title= '`确定删除${row.valueName}吗？`' @onConfirm='deleteAttrValue($index)'>
                <el-button type="danger" icon='el-icon-delete' size='mini' slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click='addOrUpdateAttr' :disabled='attrInfo.attrValueList.length<1'>保存</el-button>
        <el-button type="" @click='isShowTable=true'>取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash深拷贝
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data () {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      // 请求回来拿到并保存的数据列表
      attrList: [],
      // 是否展示属性列表
      isShowTable: true,
      // 收集新增属性||修改
      attrInfo: {
        attrName: '',// 属性名
        attrValueList: [],
        categoryId: 0,// 三级分类Id
        categoryLevel: 3, // 服务器也需要区分几级Id
      }
    }
  },
  methods: {
    getCategoryId ({categoryId, level}) {
      if (level == 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level == 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        // 代表三级分类有了，可以发请求
        this.category3Id = categoryId
        // 获取平台属性请求
        this.getAttrList ()
      }
    },
    // 获取平台属性请求
    async getAttrList () {
      const {category1Id,category2Id,category3Id} = this
      let result = await this.$API.attr.reqAttrList (category1Id,category2Id,category3Id)
      // console.log(result)
      if (result.code == 200) {
        this.attrList = result.data
      }
    },
    // 添加属性值回调
    addAttrValue () {
      // 向属性值数组里面添加元素
      this.attrInfo.attrValueList.push ({
        attrId:this.attrInfo.id,// 修改某一个属性的时候，可以在已有的属性值基础上新增，新增的时候需要把已有的属性名Id
        valueName:'',
        // 给每一个属性值打一个flag 解决查看、编辑模式切换，每个属性值之间不会相互影响
        flag: true
      })
      // 新增属性值时自动获取焦点
      this.$nextTick (() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus ()
      })
    },
    // 添加属性按钮回调
    addAttr () {
      this.isShowTable = false
      // 清除数据，解决回显问题
      this.attrInfo = {
        attrName: '',// 属性名
        attrValueList: [],
        categoryId: this.category1Id,// 收集三级分类Id
        categoryLevel: 3, // 服务器也需要区分几级Id
      }
      // 新增一条  也自动聚焦

    },
    // 修改某一个属性回调
    updateAttr (row) {
      this.isShowTable = false
      // console.log(row)
      // 由于数据结构当中存在对象套数组，数组里套对象，需要使用深拷贝解决
      // this.attrInfo = {...row}
      this.attrInfo = cloneDeep (row)
      // 处理编辑属性值时 查看与编辑模式切换
      this.attrInfo.attrValueList.forEach (item => {
        this.$set (item, 'flag', false)
      })
    },
    // 属性值切换 编辑和查看模式
    toLook (row) {
      // row是当前用户最新添加的属性值
      // 如果用户输入的空属性值，不应该变为span查看模式，需要提示
      if (row.valueName.trim() == '') {
        this.$message ('请输入正常属性值')
        return // 不执行后面的代码
      }
      // 新增的属性值不能与已有的重复
      let isRepeat = this.attrInfo.attrValueList.some (item => {
        // 判断时需要将row本身去除
        if (row !== item) {
          return row.valueName == item.valueName
        }
      })
      if (isRepeat) return
      row.flag = false
    },
    // 点击span回调变为编辑模式，且自动聚焦
    toEdit (row, index) {
      row.flag = true
      // 获取input节点，点击span，需要重绘input,需要时间，所以不会一点击就能获取到input节点，使用$nextTick()
      this.$nextTick (() => {
        // 获取input节点自动聚焦
        this.$refs[index].focus ()
      })
    },
    // 气泡确认框确认时触发
    deleteAttrValue (index) {
      // 当前删除不需要发请求
      this.attrInfo.attrValueList.splice (index, 1)
    },
    // 添加或修改保存回调
    async addOrUpdateAttr () {
      // 整理参数：1.如果用户添加了多个属性值，且属性值为空，不应该提交给服务器，过滤后在赋值给他自己
      // 提交给服务器不应该有flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter (item => {
        if (item.valueName !== '') {
          delete item.flag
          return true
        }
      })
      try {
        // 发请求，切换展示，弹出消息，重新获取列表信息请求
        await this.$API.attr.reqAddOrUpdateAttr (this.attrInfo)
        this.isShowTable = true
        this.$message ({type: 'success', message: '保存成功'})
        this.getAttrList ()
      } catch (error) {
        this.$$message ('保存失败')
      }
    }
  }
}
</script>

<style>

</style>
